<script setup>
import HeaderVue from "../../components/HeaderVue.vue";
import {ref} from 'vue'
import WriteAnswerVue from "./WriteAnswerVue.vue";
import {insertOrUpdate} from "../../../store/state.js";
import {
  getOptions,
  getPractice,
  insertOptions,
  insertPractice, listSubject, updateOptions,
  updatePractice
} from "../../../api/practice/practice.js";
import {ElMessage} from "element-plus";
import router from "../../../router/index.js";

// 单选选项
const radioOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}]);
//多选选项
const checkboxOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}])
// 判断题选项
const judgeOptions = ref([{
  value: 'T',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'F',
  content: '',
  checked: 0 // 选项未选中状态
}])

// 表单布局
const labelPosition = ref('top')
// 标题
const title = ref(['创建题目', '修改题目']);
// 难度
const difficulties = ['简单', '中等', '困难'];
// 题目类型
const types = ['单选题', '多选题', '判断题', '填空题', '简答题'];
// 所有专业(知识)
const subject = ref([]);
// 题目信息
const practice = ref({
  answer: '',
  content: "",
  difficulty: 0,
  id: 0,
  images: [],
  name: '',
  subject: "",
  type: 0,
})
// 选项对象
const option = ref({
  practiceId: 0,
  a:'',
  b:'',
  c:'',
  d:''
})

// 添加或修改题目判断并且发送接口
const handleInsertOrUpdatePractice = async () => {
  // 解析数组并且用逗号拼接
  practice.value.answer = practice.value.answer.toString();
  // console.log(practice.value)
  if (insertOrUpdate.value === 0)
    await handleInsertPractice();
  else if (insertOrUpdate.value === 1)
    await handleUpdatePractice();
}

// 添加题目
const handleInsertPractice = async () => {
  // console.log(practice.value.answer);
  // 发送请求
  await insertPractice(practice.value).then((res) => {
    // 成功后提示用户
    practice.value.id=res.data;
    // todo 可以优化
    if(isOption())handleInsertOptions(practice.value.id);
    ElMessage.success("添加题目成功")
  });
  // 跳转到题目列表
  router.back();
}

// 判断是否添加选项
const isOption = () => {
  if(practice.value.type===0){
    // console.log("单选");
    option.value.a=radioOptions.value[0].content;
    option.value.b=radioOptions.value[1].content;
    option.value.c=radioOptions.value[2].content;
    option.value.d=radioOptions.value[3].content;
    return true;
  }
  else if(practice.value.type===1){
    // console.log("多选");
    option.value.a=checkboxOptions.value[0].content;
    option.value.b=checkboxOptions.value[1].content;
    option.value.c=checkboxOptions.value[2].content;
    option.value.d=checkboxOptions.value[3].content;
    return true;
  }
  else if(practice.value.type===2){
    // console.log("判断");
    option.value.a=judgeOptions.value[0].content;
    option.value.b=judgeOptions.value[1].content;
    return true;
  }
  else return false;
}
// 选项赋值
const assignOption = () => {
  if(practice.value.type===0){
    radioOptions.value[0].content=option.value.a;
    radioOptions.value[1].content=option.value.b;
    radioOptions.value[2].content=option.value.c;
    radioOptions.value[3].content=option.value.d;
  }
  else if(practice.value.type===1){
    checkboxOptions.value[0].content=option.value.a;
    checkboxOptions.value[1].content=option.value.b;
    checkboxOptions.value[2].content=option.value.c;
    checkboxOptions.value[3].content=option.value.d;
  }
  else if(practice.value.type===2){
    judgeOptions.value[0].content=option.value.a;
    judgeOptions.value[1].content=option.value.b;
  }
}

// 选择题添加选项
const handleInsertOptions = async (id) => {
  option.value.practiceId=id;
  // console.log(option.value);
  await insertOptions(practice.value.type,option.value);
}

// 修改题目
const handleUpdatePractice = async () => {
  // 发送请求
  await updatePractice(practice.value).then(() => {
    if(isOption())handleUpdateOption(practice.value.id);
    // 成功后提示用户
    ElMessage.success("修改题目成功")
  })
  // 跳转到题目列表
  router.back();
}
// 修改题目选项
const handleUpdateOption = async (id) => {
  option.value.practiceId=id;
  console.log(option.value);
  await updateOptions(practice.value.type,option.value);
}

// 题型改变的时候将答案清空
const handleTypeChange = () => {
  practice.value.answer = [];
  console.log(practice.value.answer);
}


// 获取单个题目信息
const handleGetPractice = async () => {
  // console.log(insertOrUpdate.value);
  // console.log(practice.value.id);
  if(insertOrUpdate.value===1){
    await getPractice(Number(practice.value.id)).then(res => {
      practice.value=res.data;
      // console.log(practice.value);
      if(isOption()){
        handleGetOption(practice.value.id);
      //   改变选中状态
        handleCheckChange()
      }
    })
  }
}

// 查询题目选项
const handleGetOption = async (id) => {
  await getOptions(id).then(res => {
    console.log(practice.value.answer);
    option.value=res.data;
    // console.log(option.value);
    // 对选项赋值
    assignOption();
  })
}
// console.log(practice.value.id);
// 获取题目后获取答案到选项
const handleCheckChange=()=>{
  // 单选
  if(practice.value.type===0){
    // 将序号转换为数组
    const arr=radioOptions.value.map(item=>item.value)
    for(let i=0;i<arr.length;i++){
      if(arr[i]==practice.value.answer)radioOptions.value[i].checked=1;
    }
  }
  // 多选
  if(practice.value.type===1){
    const arr=practice.value.answer.split(',');
    practice.value.answer=arr;
    for(let i=0;i<arr.length;i++){
        const index=checkboxOptions.value.map(item=>item.value).indexOf(arr[i]);
        checkboxOptions.value[index].checked=1;
    }
    console.log(checkboxOptions.value);
  }
//   判断
  if(practice.value.type===2){
    if(practice.value.answer==='T')judgeOptions.value[0].checked=1;
    else judgeOptions.value[1].checked=1;
  }
}
// 获取专业信息
const handleListSubject=async ()=>{
  await listSubject().then(res=>{
    subject.value=res.data;
  })
}



// 获取题目id
practice.value.id=router.currentRoute.value.params.id;
// 查询单个题目
handleGetPractice();
handleListSubject();

</script>

<template>
  <el-container>
    <!--    头部导航栏-->
    <el-header class="header-outer">
      <HeaderVue></HeaderVue>
    </el-header>
    <el-main style="margin:0 0 0 260px ">
      <!--      插槽:创建或者修改题目-->
      <h2>{{ title[insertOrUpdate] }}</h2>
      <el-form
          :label-position="labelPosition"
          label-width="auto"
          :model="practice"
          style="max-width: 900px"
      >
        <el-form-item label="题目名称">
          <el-input placeholder="请输入题目名称" v-model="practice.name" style="width: 800px;height: 60px"/>
        </el-form-item>
        <el-form-item label="题目内容">
          <el-input
              v-model="practice.content"
              style="width: 800px"
              :rows="8"
              type="textarea"
              placeholder="请输入题目内容"
          />
        </el-form-item>
        <!--        题目类型选择-->
        <el-form-item label="题目类型">
          <el-radio-group v-model="practice.type" @change="handleTypeChange">
            <el-radio
                v-for="(type,index) in types"
                :key="index" :value="index"
                size="large"
                border
                style="margin-right: 10px"
                @change="practice.type=index"
            >{{ type }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <WriteAnswerVue :practice="practice" :radioOptions="radioOptions" :judge-options="judgeOptions" :checkbox-options="checkboxOptions"></WriteAnswerVue>
        <!--      难度选择  -->
        <el-form-item label="难度">
          <el-radio-group
              v-model="practice.difficulty"
          >
            <el-radio
                :value="index"
                v-for="(difficulty,index) in difficulties" :key="index"
                size="large"
                border
                style="margin-right: 40px"
            >
              {{ difficulty }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--知识点-->
        <el-form-item label="知识点">
          <el-select
              v-model="practice.subject"
              placeholder="选择知识点"
              size="large"
              style="width: 240px"
          >
            <el-option
                v-for="item in subject"
                :key="item"
                :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-main>
    <!--    底部按钮-->
    <el-footer>
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="handleInsertOrUpdatePractice">保存题目</el-button>
    </el-footer>
  </el-container>
</template>

<style scoped lang="less">
.header-outer {
  height: 100%;
  // 改变盒子背景 略灰一点
  background-color: #fff;
  // 改变外部盒子边界线便于区分
  border-bottom: 2px solid #eee;
  // 设置盒子底部阴影
  box-shadow: 0 2px 8px 0 rgba(7, 17, 27, 0.06);
}
.el-container {
  min-height: 100vh;
}

</style>